package com.example.eventbus

import com.example.eventbus.handler.AsyncEventHandler
import com.example.eventbus.handler.EventHandler
import com.example.eventbus.handler.MainEventHandler
import com.example.eventbus.handler.PostEventHandler
import com.hil.eventbus.Subscription
import com.hil.eventbus.ThreadMode
import java.util.concurrent.CopyOnWriteArrayList

object EventDispatcher {
    /** MAIN 线程 UI 线程 */
    private val mainEventHandler = MainEventHandler()
    /** POST 线程即事件发出的线程 */
    private val postEventHandler = PostEventHandler()
    /** BACKGROUND 线程，ExecutorService 线程池 */
    private val asyncHandler = AsyncEventHandler()

    fun dispatcherEvent(event : IEvent, list:CopyOnWriteArrayList<Subscription>){
        list.forEach {
           val weakSubscriber = it.subscriber.get()
           val _this = it
           weakSubscriber?.let {
                val eventHandler = getEventHandler(_this.threadMode)
                eventHandler.handleEvent(_this,event)
           }
        }
    }

    fun getEventHandler( mode : ThreadMode):EventHandler{
        return when(mode){
            ThreadMode.MAIN -> mainEventHandler
            ThreadMode.BACKGROUND -> asyncHandler
            else -> postEventHandler
        }
    }
}